package com.hall.controller;

import com.hall.pojo.ConfigBeanValue;
import com.hall.pojo.*;
import com.hall.pojo.common.Result;
import com.hall.service.UserService;
import com.hall.utils.UUIDCode;
import com.hall.utils.UserSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 用户操作,注册,登录等
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class SysUserController {
    @Autowired
    UserService userService;
    @Autowired
    private ConfigBeanValue configBeanValue;
    //密码登录
    @ResponseBody
    @RequestMapping("/checkLogin")
    public String checkLogin(HttpServletRequest request, String username, String password) {
        System.out.println(configBeanValue.toString());
        if (username == null || password == null) {
            return "loginFalse";
        }
        UserLogin userLogin = new UserLogin()
                .setLoginName(username)
                .setPassword(password);
        SysUser sysUser3 = userService.checkLogin(userLogin);
        if (sysUser3 != null) {
            if (password.equals(sysUser3.getPassword())) {
                return sysUser3.getLoginName()+"&"+sysUser3.getPassword();
            }
        }
        return "loginFalse";
    }

    //验证码登录
    @ResponseBody
    @RequestMapping(value = "/checkLoginByCaptcha",produces = {"application/json;charset=UTF-8"})
    public String RetrievePassword(String phone, String captcha, HttpSession session, HttpServletRequest request) {
        //判断输入验证码与接收的是否一致
        if (captcha.equals(session.getAttribute(phone))) { //固定字符串虽无使用问题，但改为用手机号码做key可防止高并发可能带来的问题
            //构建对象
            UserLogin userLogin3 = new UserLogin()
                    .setPhone(phone);
            //查询手机绑定用户是否存在
            SysUser sysUser4 = userService.checkLoginByPhone(userLogin3);
            System.out.println("验证码查询的用户对象为"+sysUser4);
            if (sysUser4 != null) {
                session.removeAttribute(phone);//登录成功后清除session存的验证码
                return sysUser4.getLoginName()+"&"+sysUser4.getPassword();
            }
        }
        return "loginFalse";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    @RequestMapping("/loginAuto")
    public String loginAuto(){return "login-befor";}
    //提交注册表单
    @ResponseBody
    @RequestMapping("/submitRegister")
    public Result<String> submitRegister(RegisterVo registerVo) {
        //取出表单数据实例化用户对象(需要生成随机邀请码和随机用户id)
        String loginName= registerVo.getLoginName();
        String phone= registerVo.getPhone();
        String password = registerVo.getPassword();
        String userType = registerVo.getUserType();

        String[] list ={"assistant","admin","doctor","patient","other"};

        List<String> check =new ArrayList<String>(list.length);
        Collections.addAll(check,list);

        //phone 注册不用再填手机号。用户在loginName中填手机号
        if(loginName==null ||  password==null||userType==null){
            return Result.error("存在未填项" );
        }
        if(!check.contains(userType)){
            return Result.error("不存在的用户类型");
        }
        // 查询手机号phone字段 和用户名login_name字段 是否已被注册
        SysUser user1 = userService.selectUsername(registerVo);
        SysUser user2 = userService.selectPhone(registerVo);

        //只判断loginName（手机号）
        if (user1 != null)return Result.error("当前登录账号已被注册");
        //if (user2 != null)return Result.error("当前手机号已注册");

        SysUser user3 = new SysUser();
        String uuid = UUIDCode.generateShortUuid();

        // 2023.2.24 lyy 注册
        String username =registerVo.getName();
        if( username == null )
          username ="u"+(int) ((Math.random() * 9 + 1) * 100000) + "";

        user3.setId(uuid); //8位uuid,每4组模62算法

        user3.setLoginName(loginName);
        user3.setPhone(loginName); //登录账号就是手机号

        user3.setUsertype(userType);
        user3.setPassword(password);

        user3.setRecommender(registerVo.getInviteCode()); //我的推荐人码

        user3.setInviteCode("qa" + UUIDCode.generateShortUuid().substring(0,4)); //我的推广码
        user3.setCreateDate(new Timestamp(System.currentTimeMillis()));//注册时间

        user3.setName(username);

        int i = userService.addUser(user3);
        if (i > 0) {
            SysUserPermission sysUserPermission=new SysUserPermission()
                    .setUserId(uuid)
                    .setIsAttestation(configBeanValue.getIsAttestation())
                    .setMakeAppointment(configBeanValue.getMakeAppointment())
                    .setByAppointment(configBeanValue.getByAppointment())
                    .setIsshow(configBeanValue.getIsShow())
                    .setUserName(username)
                    .setUserType(userType);
            boolean c = userService.addUserPermission(sysUserPermission);
            return c?(Result.success(null,"注册成功")):(Result.error("注册失败"));
        }
        return Result.success(null,"注册成功");
    }

    //获取用户权限
    @ResponseBody
    @GetMapping("/permission")
    public R userPermission(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        SysUserPermission userPermission = userService.userPermission(userId);
        return new R(userPermission != null, "获取用户所有权限请求", userPermission);
    }

    //用户隐私条款
    @GetMapping("/terms/{index}")
    public String Terms(@PathVariable int index){
        if(index==1){
            return "use_protocol";
        }else{
            return "use_privacy";
        }
    }

    //boke项目调用用户对象的接口(弃用/勿删)
    @ResponseBody
    @GetMapping("/getUserById/{id}")
    public SysUser getUserById(@PathVariable String id){
        return userService.getUser(id);
    }

    @ResponseBody
    @GetMapping("/getUser")
    public  Result<List<SysUser>> getAll(){
        List<SysUser> all = userService.allUser();
        if(all.size()!=0){
           return Result.success(all,"获取成功");
        }else{
           return Result.error("请求失败");
        }
    }
    @ResponseBody
    @GetMapping("/getUser/{id}")
    public Result<SysUser> get(@PathVariable String id){
        SysUser sys = userService.getUser(id);
        if(sys==null){
           return Result.error("无匹配的用户对象");
        }else {
           return Result.success(sys, "获取成功");
        }
    }



    //当前登录用户接口
    @ResponseBody
    @GetMapping("/getLogging")
    public Result<SysUser>getLoggingUser(HttpServletRequest request){
       String id = UserSession.getSysUser(request).getId();
       if(id==null || id.isEmpty()){
           return Result.error("请求失败:当前无已登录用户");
       }
       SysUser sysUser = userService.getUser(id);
       return Result.success(sysUser,"请求成功");
    }
}